<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">{{ '登录 HR- LinkEase' }}</div>
    <div class="login-form-sub-title">{{ ' HR - 领壹制造' }}</div>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-form
      ref="loginForm"
      :model="userInfo"
      class="login-form"
      layout="vertical"
      @submit="handleSubmit"
    >
      <a-form-item
        field="account"
        :rules="[{ required: true, message: '用户名不能为空' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input v-model="userInfo.account" :placeholder="'用户名'">
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        field="password"
        :rules="[{ required: true, message: '密码不能为空' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password
          v-model="userInfo.password"
          :placeholder="'密码'"
          allow-clear
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox
            checked="rememberPassword"
            :model-value="rememberPassword"
            @change="(e)=> setRememberPassword(e as boolean)"
          >
            {{ '记住密码' }}
          </a-checkbox>
          <a-link @click="modelFormType = 'resetPwd'">{{ '忘记密码' }}</a-link>
        </div>
        <a-button type="primary" html-type="submit" long :loading="loading">
          {{ '登录' }}
        </a-button>
        <!-- <a-button type="text" long class="login-form-register-btn">
          {{ '重置密码' }}
        </a-button> -->
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { Message } from '@arco-design/web-vue';
import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
// import { useI18n } from 'vue-i18n';
import { useStorage } from '@vueuse/core';
import { useUserStore } from '@/store';
import useTenantStore from '@/store/modules/client/tenant/index';
import { useVModel } from '@vueuse/core';
import useLoading from '@/hooks/loading';
// import type { LoginData } from '@/api/user';
import {
  VerifyLogin,
  TenantChange,
  getTokenByUcodeWithCcode
} from '@/apis/platform/index';

const props = withDefaults(
  //参数说明
  defineProps<{
    formType?: string;
    regex?: {
      [name: string]: {
        role: any;
        name: any;
      };
    };
  }>(),
  {}
);
const emits = defineEmits(['update:formType']);
const modelFormType = useVModel(props, 'formType', emits);
const router = useRouter();
// const { t } = useI18n();
const errorMessage = ref('');
const { loading, setLoading } = useLoading();
const userStore = useUserStore();
const tenantStore = useTenantStore();

// const loginConfig = useStorage('login-config', {
//   rememberPassword: true,
//   username: '13900000000', // 演示默认值
//   password: '123', // demo default value
// });
// const userInfo = reactive({
//   username: loginConfig.value.username,
//   password: loginConfig.value.password,
// });

let rememberPassword = ref(true);
const userInfo = reactive({
  account: '13900000001',
  password: 'lke888888'
  // username: '13900000000',
  // password: '123'
});

const handleSubmit = async ({
  errors,
  values
}: {
  errors: Record<string, ValidatedError> | undefined;
  values: Record<string, any>;
}) => {
  if (loading.value) return;
  if (!errors) {
    setLoading(true);
    try {
      // const res = await userStore.login(values as any, 'admin');
      // const { redirect, ...othersQuery } = router.currentRoute.value.query;
      // router.push({
      //   name: (redirect as string) || 'WorkPlace',
      //   query: {
      //     ...othersQuery
      //   }
      // });
      // Message.success('欢迎使用 ');
      // // const { rememberPassword } = values;
      // const { username, password } = values;
      const resLogin = await VerifyLogin({ ...values, loginType: 1 });

      if (resLogin.code) {
        Message.warning(resLogin.msg);
        return;
      }
      tenantStore.setTenantCode(resLogin);
      //验证登录租户
      const tenantCodeList = Object.keys(resLogin);
      const strCode = tenantCodeList.join(',');
      // const base64 = btoa(strCode); //加密
      // console.log('base64', base64);
      // 获取租户列表
      tenantStore.getTenantListByCode(strCode);
      // 根据条件获取token,默认选第一个租户
      const cCode: any = tenantCodeList[0];
      let uCode = '';
      for (const key in resLogin) {
        if (Object.prototype.hasOwnProperty.call(resLogin, key)) {
          const element = resLogin[key];
          if (key === cCode) {
            uCode = element;
          }
        }
      }
      tenantStore.setCurrentTenantCode(cCode);
      const res = await userStore.login(cCode, uCode, 'admin');
      const { redirect, ...othersQuery } = router.currentRoute.value.query;

      router.push({
        name: (redirect as string) || 'WorkPlace',
        query: {
          ...othersQuery
        }
      });
      // Message.success('欢迎使用 ');
      // // const { rememberPassword } = values;
      // const { username, password } = values;
      // 实际生产环境需要进行加密存储。
      // The actual production environment requires encrypted storage.
      // userInfo.username = rememberPassword ? username : '';
      // userInfo.password = rememberPassword ? password : '';
    } catch (err) {
      errorMessage.value = (err as Error).message;
    } finally {
      setLoading(false);
    }
  }
};
const setRememberPassword = (value: boolean) => {
  rememberPassword.value = value;
};
</script>

<style lang="less" scoped>
.login-form {
  &-wrapper {
    width: 320px;
  }

  &-title {
    color: var(--color-text-1);
    font-weight: 500;
    font-size: 24px;
    line-height: 32px;
  }

  &-sub-title {
    color: var(--color-text-3);
    font-size: 16px;
    line-height: 24px;
  }

  &-error-msg {
    height: 32px;
    color: rgb(var(--red-6));
    line-height: 32px;
  }

  &-password-actions {
    display: flex;
    justify-content: space-between;
  }

  &-register-btn {
    color: var(--color-text-3) !important;
  }
}
</style>
